//
// Created by 原帅 on 2022/10/2.
//

#include "RSignalCenter.h"
#include "stdio.h"
#include "RLog.h"

#define MAX_SIGNAL_NUM 32

map<int, vector<RSigProcIF *>> RSignalCenter::SigInterfaces;

int RSignalCenter::RegisterSignalAll() {
    for (int sigNum = 1 ;sigNum<=MAX_SIGNAL_NUM;sigNum++) {
        if (sigNum) {
            RegisterSignal(sigNum);
        }
    }
    return 0;
}

int RSignalCenter::RegisterSignal(int sigNum) {
    if (sigNum) {
        signal(sigNum, (void (*)(int)) RSignalCenter::SignalProcess);
        RLogDbg("info:%s,signal number %d",__func__ ,sigNum);
    }
    return 0;
}

void RSignalCenter::SignalProcess(int sigNum) {
    RLogDbg("callback: %s: sigNum:%d", __func__, sigNum);
    if (RSignalCenter::SigInterfaces.count(sigNum)) {
        for (auto proc: RSignalCenter::SigInterfaces[sigNum]) {
            proc->signalProc();
        }
    }
}

int RSignalCenter::AddSignalProcessor(int sigNum, RSigProcIF *sigIf) {
    if (sigIf == nullptr) return -1;
    if (SigInterfaces.count(sigNum)) {
        /// 追加
        vector<RSigProcIF *> &vecRSigIFs = SigInterfaces[sigNum];
        for (auto sif:vecRSigIFs) {
            if (sif == sigIf) return 0;
        }
        vecRSigIFs.push_back(sigIf);
    } else {
        /// 新建
        vector<RSigProcIF *> vecRSigIFs;
        vecRSigIFs.push_back(sigIf);
        SigInterfaces.insert(pair<int, vector<RSigProcIF *>>(sigNum, vecRSigIFs));
        RegisterSignal(sigNum);
    }
    return 0;
}
